package net.alche.fa.core.doing;
import net.alche.fa.core.model.Logic;
import net.alche.fa.core.model.FaValue;
import net.alche.fa.core.CodeLevel;
import net.alche.fa.core.SageStone;
import net.alche.fa.core.FaException;
import java.lang.reflect.Array;

//
// 中括号 [ ]
//
@FaAnnoDoing
public class BracketSquareDo extends AbstractDoing {

  @Override
  public boolean matched(String what, Logic g) {
    return "[".equals(what);
  }

  @Override
  public FaValue doing(Logic g, CodeLevel lvl, SageStone st) throws FaException {
    FaValue val = getLogicObjVal(st, lvl, g);
    if (val.isNull()) {
      throw new FaException(FaException.NULL_ERROR, "obj[xx] obj is null");
    }
    FaValue fav = super.getLogicDataVal(st, lvl, g);
    if (val.isNull()) {
      throw new FaException(FaException.NULL_ERROR, "xx[val] val is null");
    }
    if (val.getType() == FaValue._ARR) {
      int index = fav.getIntValue().intValue();
      Object item = Array.get(val.getValue(), index);
      FaValue itemVal = new FaValue(item);
      if (item == null) {
        itemVal.setObjType(this.plat.getInnterType(val.getObjType()));
        if (this.plat.isSageName(itemVal.getObjType())) {
          itemVal.setType(FaValue._SAGE);
        }
        else {
          itemVal.setType(FaValue.getChar(itemVal.getObjType()));
        }
        itemVal.setParObj(val);
        itemVal.setElIndex(index);
      }
      return itemVal;
    }
    return null;
  }
}